package phenix.com.phenixdemo.control;

import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;

import java.util.Arrays;
import java.util.List;

import phenix.com.phenixdemo.ActivityMain;

/**
 * Created by zhouphenix on 2016-3-13.
 */
public class ListViewService extends RemoteViewsService {


    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {

        return new ListRemoteViewsFactory(this, Arrays.asList(ActivityMain.itemTitles));
    }

    private static class ListRemoteViewsFactory implements RemoteViewsFactory {

        private Context mContext;
        private List<String> mList;

        public ListRemoteViewsFactory(Context mContext, List<String> mList) {
            this.mContext = mContext;
            this.mList = mList;
        }

        @Override
        public void onCreate() {

        }

        @Override
        public void onDataSetChanged() {

        }

        @Override
        public void onDestroy() {
            mList.clear();
            mList = null;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public RemoteViews getViewAt(int position) {
            //这个方法相当于返回ListView的一个Item(类似Adapter里面的getView/getItem吧)
            RemoteViews rv = new RemoteViews(mContext.getPackageName(), android.R.layout.simple_list_item_1);
            rv.setTextViewText(android.R.id.text1, mList.get(position));
            //这里intent起到传数据的作用--new Intent()是否带参数不影响
            Intent fillInIntent = new Intent(mContext,WidgetClickHandlerService.class);
            fillInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            fillInIntent.putExtra("clicked_position",position);
            fillInIntent.putExtra("clicked_item", mList.get(position));
            //记住,这里是不可以用setOnClickPendingIntent的,官方API上有说, PendingIntent对于CollectionViews是无效的.
            rv.setOnClickFillInIntent(android.R.id.text1, fillInIntent);
            return rv;
        }

        @Override
        public RemoteViews getLoadingView() {
            //when ListView is scrolled, the loading view is not necessary
            //如果是StackView之类需要显示图片什么的,滑动的时候免得用户看到白板,就设置个Loading的View
            return null;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }
    }
}
